package com.financing.platform.web;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.financing.platform.dto.GroupDTO;
import com.financing.platform.dto.UserGroupDTO;
import com.financing.platform.dto.UserInfoDTO;
import com.financing.platform.service.IAccessControlService;
import com.financing.platform.service.IGroupService;
import com.financing.platform.service.IUserGroupService;
import com.financing.platform.service.IUserInfoService;
import com.financing.platform.util.DTOdateSet;
import com.financing.platform.util.Dict;
import com.financing.platform.util.MemcacheCacheHelper;
import com.financing.platform.util.StringUtil;

/**
 * 
* @ClassName: UserInfoAction 
* @Description: 用户信息 
* @author chenming 
* @date 2014年7月27日 下午4:58:38 
*
 */
@Controller
public class UserInfoAction extends BaseAction {

	@Autowired
	private IUserInfoService userInfoServiceImpl;
	
	@Autowired
	private IAccessControlService accessControlServiceImpl;
	
	@Autowired
	private IGroupService groupServiceImpl;
	
	@Autowired
	private IUserGroupService userGroupServiceImpl;
	
	/**
	 * 
	* @Title: login 
	* @Description: 用户登录
	* @param   request
	* @param   response
	* @param   accessInfoDto
	* @return ModelAndView   
	* @throws
	 */
	@RequestMapping("/login.shtml")
	public ModelAndView login(HttpServletRequest request,
			HttpServletResponse response,UserInfoDTO userInfoDTO) {
		
		HttpSession session = request.getSession();
		
		this.log.info("Begin login!");
		
		log.info("verifyCode result is "+checkVerifyCode(request));
		//if(checkVerifyCode(request)){
			
			boolean loginStatus = false;
			
			if(null != userInfoDTO && null != userInfoDTO.getUserNickname() && null != userInfoDTO.getPassword()){
				loginStatus = userInfoServiceImpl.userLogin(userInfoDTO);
			}
			
			if(loginStatus){
				UserInfoDTO user = userInfoServiceImpl.queryUserInfo(userInfoDTO);
				MemcacheCacheHelper.mcc.set(user.getUserId()+user.getUserNickname()+request.getServerName(), session.getId());
				session.setAttribute(DTOdateSet.user,user );
				//设置首页leftmenu选中
				session.setAttribute(Dict.requestID, "index.shtml");
				this.log.info("End login!");
				return new ModelAndView("index");
			}
			
		//}
		return new ModelAndView("login");
	}

	/**
	 * 
	* @Title: checkCode 
	* @Description: 校验动态验证码
	* @param @param request
	* @param @return    
	* @return boolean   
	* @throws
	 */
	private boolean checkVerifyCode(HttpServletRequest request){
		String code = request.getParameter("code");
		String seesionCode = (String) request.getSession().getAttribute("code");
		if(code == null || seesionCode == null){
			return false;
		}
		return seesionCode.equals(code);
	}
	
	/**
	 * 
	* @Title: loginPer 
	* @Description: 准备登陆页
	* @param   request
	* @param   response
	* @return ModelAndView   
	* @throws
	 */
	@RequestMapping("/loginPer.shtml")
	public ModelAndView loginPer(HttpServletRequest request,
			HttpServletResponse response) {
		request.getSession().setAttribute(Dict.requestID, "loginPer.shtml");
		return new ModelAndView("login");
	}
	
	/**
	 * 
	* @Title: index 
	* @Description: 显示首页
	* @param   request
	* @param   response
	* @return ModelAndView   
	* @throws
	 */
	@RequestMapping("/index.shtml")
	public ModelAndView index(HttpServletRequest request,
			HttpServletResponse response){
		request.getSession().setAttribute(Dict.requestID, "index.shtml");
		return new ModelAndView("index");
	}
	
	/**
	 * 
	* @Title: queryAllUser 
	* @Description:  查询所有用户
	* @param @param request
	* @param @param response
	* @param @param userInfoDTO
	* @return ModelAndView   
	* @throws
	 */
	@RequestMapping("/queryAllUser.shtml")
	public ModelAndView queryAllUser(HttpServletRequest request,
			HttpServletResponse response,UserInfoDTO userInfoDTO){
		
		List<UserInfoDTO> list = userInfoServiceImpl.queryAllUserInfo(userInfoDTO);
		Map<String,Object> mode = new HashMap<String,Object>();
		
		mode.put("userList", list);
		mode.put("useInfoDTO", userInfoDTO);
		
		return new ModelAndView("userList",mode);
	}
	
	/**
	 * 
	* @Title: user 
	* @Description: 查询单用户信息
	* @param   request
	* @param   response
	* @param   userInfoDTO
	* @return ModelAndView   
	* @throws
	 */
	@RequestMapping("/queryUserInfo.shtml")
	public ModelAndView user(HttpServletRequest request,
			HttpServletResponse response,UserInfoDTO userInfoDTO){
		
		UserInfoDTO userInfo = userInfoServiceImpl.queryUserInfo(userInfoDTO);
		
		List<GroupDTO> allGroups = groupServiceImpl.queryAllGroup(new GroupDTO());
		
		UserGroupDTO userGroupDto = new UserGroupDTO();
		userGroupDto.setUserId(userInfoDTO.getUserId());
		List<UserGroupDTO> selectGroups = userGroupServiceImpl.queryUserGroup(userGroupDto);
		
		Map<String,Object> mode = new HashMap<String,Object>();
		mode.put("userInfo", userInfo);
		mode.put("allGroups", allGroups);
		mode.put("selectGroups", selectGroups);
		
		return new ModelAndView("userModify",mode);
	}
	
	/**
	 * 
	* @Title: updateUserInfo 
	* @Description:  更新用户信息
	* @param   request
	* @param   response
	* @param   userInfoDTO
	* @return ModelAndView   
	* @throws
	 */
	@RequestMapping("/updateUserInfo.shtml")
	public ModelAndView updateUserInfo(HttpServletRequest request,
			HttpServletResponse response,UserInfoDTO userInfoDTO){
		
		UserInfoDTO userInfo = userInfoServiceImpl.updateUserInfo(userInfoDTO);
		
		String[] groupsId = request.getParameterValues("groupId");
		
		UserGroupDTO userGroupDto = new UserGroupDTO();
		userGroupDto.setUserId(userInfoDTO.getUserId());
		userGroupServiceImpl.deleteUserGroup(userGroupDto);
		
		DTOdateSet.setCreateInfo(userGroupDto, request.getSession());
		DTOdateSet.setUpdateInfo(userGroupDto, request.getSession());
		
		if(groupsId != null){
			userGroupServiceImpl.saveUserGroup(groupsId,userGroupDto);
		}
		
		List<GroupDTO> allGroups = groupServiceImpl.queryAllGroup(new GroupDTO());
		List<UserGroupDTO> selectGroups = userGroupServiceImpl.queryUserGroup(userGroupDto);
		
		Map<String,Object> mode = new HashMap<String,Object>();
		mode.put("userInfo", userInfo);
		mode.put("allGroups", allGroups);
		mode.put("selectGroups", selectGroups);
		
		return new ModelAndView("userModifyResult",mode);
	}
	
	/**
	 * 
	* @Title: logout 
	* @Description: 登出
	* @param   request
	* @param   response
	* @return ModelAndView   
	* @throws
	 */
	@RequestMapping("/logout.shtml")
	public ModelAndView logout(HttpServletRequest request,
			HttpServletResponse response){
	
		request.getSession().invalidate();
		
		Cookie[] cookies = request.getCookies();  
		for(int i=0;i<cookies.length;i++){  
			Cookie cookie = new Cookie(cookies[i].getName(), null);  
			cookie.setMaxAge(0);
			response.addCookie(cookie);
		}

		return new ModelAndView("login");
	}
	
	@RequestMapping("/addUser.shtml")
	public ModelAndView addUser(HttpServletRequest request,HttpServletResponse response,UserInfoDTO userInfo){
		DTOdateSet.setCreateInfo(userInfo, request.getSession());
		DTOdateSet.setUpdateInfo(userInfo, request.getSession());
		userInfoServiceImpl.addUserInfo(userInfo);
		return new ModelAndView("index");
	}
	

	@RequestMapping("/viewVerifyCode.shtml")
	public void viewVerifyCode(HttpServletRequest request, HttpServletResponse response){
		HttpSession session = request.getSession();
		try {
			String code = StringUtil.createRandomChineseCharactersImage(response.getOutputStream());
			log.info("verifyCode is :"+code);
			session.setAttribute("code",code);
		} catch (Exception e) {
			log.error("create random chinese characters image error!",e);
		}finally{
			try {
				response.getOutputStream().flush();
			} catch (IOException e) {
				log.error("resopnse out image error",e);
			}
		}
		return ;
	} 

}
